package thread.unit3.previousdeadlock;

/**
 * @program: ThreadDemo
 * @description:
 * @author: 作者
 * @create: 2021-06-24 20:59
 */
 class LockDemo1 implements Runnable {

    @Override
    public void run() {

        while (true) {
            //加同步锁
            synchronized (Test.A) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Ab");
//                try {
//                    Test.A.wait();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                synchronized (Test.B){
                    System.out.println("线程1");
                }
//                System.out.println("卡1余额：" + Thread.currentThread().getName() + ":" + Test.card1--);

//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println("卡2余额："+Thread.currentThread().getName()+":"+Test.card2++);
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        }
    }
}
class Lock2 implements Runnable{

    @Override
    public void run() {
        while (true) {
        //加同步锁
        synchronized (Test.B) {
            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Bb");
            synchronized (Test.A){
                //Test.A.notify();
                System.out.println("线程2");
            }
//                System.out.println("卡2余额：" + Thread.currentThread().getName() + ":" + Test.card2--);

//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println("卡1余额："+Thread.currentThread().getName()+":"+Test.card1++);
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
        }
        }
    }
}

public class Test{
//    public  static int card2=0;
//    public static int card1 = 10;
    public static Object A=new Object();
    public static Object B=new Object();
    public static void main(String[] args) {
        LockDemo1 d1 = new LockDemo1();
        Lock2 d2 = new Lock2();
        Thread t1 = new Thread(d1,"线程1");
        Thread t2 = new Thread(d2,"线程2");
        // Thread t3 = new Thread(d1);
        t1.start();
        t2.start();
    }
}


